import { defineStore } from 'pinia'

/**
 * 照片状态管理
 */
export const usePhotoStore = defineStore('photo', {
  state: () => ({
    // 照片列表
    photos: [] as any[],
    
    // 当前照片
    currentPhoto: null as any,
    
    // 分页信息
    pagination: {
      page: 1,
      limit: 50,
      total: 0,
      totalPages: 0
    },
    
    // 加载状态
    loading: false,
    
    // 选中照片
    selectedPhotos: [] as number[],
    
    // 缩略图缓存
    thumbnailCache: new Map<string, string>()
  }),
  
  getters: {
    // 获取照片总数
    photoCount: (state) => state.pagination.total,
    
    // 获取当前页照片
    currentPagePhotos: (state) => state.photos,
    
    // 获取选中照片数量
    selectedCount: (state) => state.selectedPhotos.length,
    
    // 获取选中照片列表
    selectedPhotoList: (state) => {
      return state.photos.filter(photo => state.selectedPhotos.includes(photo.id))
    },
    
    // 检查照片是否选中
    isPhotoSelected: (state) => (photoId: number) => {
      return state.selectedPhotos.includes(photoId)
    }
  },
  
  actions: {
    // 获取照片列表
    async fetchPhotos(params: any = {}) {
      this.loading = true
      
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，返回模拟数据')
          // 模拟数据用于开发环境
          this.photos = []
          this.pagination = {
            page: 1,
            limit: 20,
            total: 0,
            totalPages: 0
          }
          return
        }
        
        const response = await window.electronAPI.photos.getList({
          page: params.page || this.pagination.page,
          limit: params.limit || this.pagination.limit,
          orderBy: params.orderBy || 'captured_at',
          orderDirection: params.orderDirection || 'desc',
          filters: params.filters || {}
        })
        
        if (response.success) {
          this.photos = response.data.photos
          this.pagination = {
            page: response.data.page,
            limit: response.data.limit,
            total: response.data.total,
            totalPages: response.data.totalPages
          }
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取照片列表失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 获取照片详情
    async fetchPhotoById(id: number) {
      this.loading = true
      
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，返回null')
          return null
        }
        
        const response = await window.electronAPI.photos.getById({ id })
        
        if (response.success) {
          this.currentPhoto = response.data
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取照片详情失败:', error)
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新照片信息
    async updatePhoto(id: number, updates: any) {
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，模拟更新操作')
          return null
        }
        
        const response = await window.electronAPI.photos.update({ id, updates })
        
        if (response.success) {
          // 更新本地照片列表中的对应项
          const index = this.photos.findIndex(photo => photo.id === id)
          if (index !== -1) {
            this.photos[index] = { ...this.photos[index], ...updates }
          }
          
          // 更新当前照片
          if (this.currentPhoto && this.currentPhoto.id === id) {
            this.currentPhoto = { ...this.currentPhoto, ...updates }
          }
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('更新照片失败:', error)
        throw error
      }
    },
    
    // 删除照片
    async deletePhoto(id: number) {
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，模拟删除操作')
          return null
        }
        
        const response = await window.electronAPI.photos.delete({ id })
        
        if (response.success) {
          // 从本地照片列表中移除
          this.photos = this.photos.filter(photo => photo.id !== id)
          
          // 从选中列表中移除
          this.selectedPhotos = this.selectedPhotos.filter(photoId => photoId !== id)
          
          // 如果是当前照片，清空当前照片
          if (this.currentPhoto && this.currentPhoto.id === id) {
            this.currentPhoto = null
          }
          
          // 更新总数
          this.pagination.total -= 1
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('删除照片失败:', error)
        throw error
      }
    },
    
    // 获取照片缩略图
    async getThumbnail(id: number): Promise<string> {
      // 检查缓存
      if (this.thumbnailCache.has(id.toString())) {
        return this.thumbnailCache.get(id.toString())!
      }
      
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，返回空字符串')
          return ''
        }
        
        const response = await window.electronAPI.photos.getThumbnail({ id })
        
        if (response.success) {
          // 缓存缩略图路径
          this.thumbnailCache.set(id.toString(), response.data)
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('获取缩略图失败:', error)
        throw error
      }
    },
    
    // 选择照片
    selectPhoto(id: number) {
      if (!this.selectedPhotos.includes(id)) {
        this.selectedPhotos.push(id)
      }
    },
    
    // 取消选择照片
    deselectPhoto(id: number) {
      this.selectedPhotos = this.selectedPhotos.filter(photoId => photoId !== id)
    },
    
    // 切换照片选择状态
    togglePhotoSelection(id: number) {
      if (this.selectedPhotos.includes(id)) {
        this.deselectPhoto(id)
      } else {
        this.selectPhoto(id)
      }
    },
    
    // 全选照片
    selectAllPhotos() {
      this.selectedPhotos = this.photos.map(photo => photo.id)
    },
    
    // 取消全选
    deselectAllPhotos() {
      this.selectedPhotos = []
    },
    
    // 设置当前页
    setPage(page: number) {
      this.pagination.page = page
      this.fetchPhotos()
    },
    
    // 设置每页数量
    setLimit(limit: number) {
      this.pagination.limit = limit
      this.fetchPhotos()
    },
    
    // 批量删除照片
    async deletePhotos(ids: number[]) {
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，模拟批量删除操作')
          return null
        }
        
        const response = await window.electronAPI.photos.deleteMultiple({ ids })
        
        if (response.success) {
          // 从本地照片列表中移除
          this.photos = this.photos.filter(photo => !ids.includes(photo.id))
          
          // 从选中列表中移除
          this.selectedPhotos = this.selectedPhotos.filter(photoId => !ids.includes(photoId))
          
          // 如果当前照片在删除列表中，清空当前照片
          if (this.currentPhoto && ids.includes(this.currentPhoto.id)) {
            this.currentPhoto = null
          }
          
          // 更新总数
          this.pagination.total -= ids.length
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('批量删除照片失败:', error)
        throw error
      }
    },
    
    // 批量更新照片
    async updatePhotos(ids: number[], updates: any) {
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，模拟批量更新操作')
          return null
        }
        
        const response = await window.electronAPI.photos.updateMultiple({ ids, updates })
        
        if (response.success) {
          // 更新本地照片列表中的对应项
          this.photos = this.photos.map(photo => {
            if (ids.includes(photo.id)) {
              return { ...photo, ...updates }
            }
            return photo
          })
          
          // 如果当前照片在更新列表中，更新当前照片
          if (this.currentPhoto && ids.includes(this.currentPhoto.id)) {
            this.currentPhoto = { ...this.currentPhoto, ...updates }
          }
          
          return response.data
        } else {
          throw new Error(response.error)
        }
      } catch (error) {
        console.error('批量更新照片失败:', error)
        throw error
      }
    },
    
    // 切换照片收藏状态
    async togglePhotoFavorite(id: number) {
      const photo = this.photos.find(p => p.id === id)
      if (!photo) return
      
      const isFavorite = !photo.is_favorite
      await this.updatePhoto(id, { is_favorite: isFavorite })
      return isFavorite
    },
    
    // 更新照片评分
    async updatePhotoRating(id: number, rating: number) {
      await this.updatePhoto(id, { rating })
    },
    
    // 设置排序
    setSort(orderBy: string, orderDirection: 'asc' | 'desc' = 'desc') {
      // 保存排序参数
      this.sortBy = orderBy
      this.sortDirection = orderDirection
      
      // 重新获取照片
      this.fetchPhotos({
        orderBy,
        orderDirection
      })
    },
    
    // 加载更多照片
    async loadMore() {
      if (this.loading || !this.hasMore) return
      
      const nextPage = this.pagination.page + 1
      
      try {
        // 检查是否在Electron环境中
        if (typeof window.electronAPI === 'undefined') {
          console.log('不在Electron环境中，模拟加载更多操作')
          return
        }
        
        const response = await window.electronAPI.photos.getList({
          page: nextPage,
          limit: this.pagination.limit,
          orderBy: this.sortBy || 'captured_at',
          orderDirection: this.sortDirection || 'desc',
          filters: {}
        })
        
        if (response.success) {
          // 添加新照片到现有列表
          this.photos = [...this.photos, ...response.data.photos]
          this.pagination.page = response.data.page
        }
      } catch (error) {
        console.error('加载更多照片失败:', error)
      }
    },
    
    // 清空照片列表
    clearPhotos() {
      this.photos = []
      this.currentPhoto = null
      this.selectedPhotos = []
    },
    
    // 清空缩略图缓存
    clearThumbnailCache() {
      this.thumbnailCache.clear()
    }
  }
})